package com.ellricky.baselib.ui.order

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.fragment.BaseFragment
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.widget.refresh.RvRefreshListener
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.dialog.picker.EPickerUtil
import com.ellricky.baselib.entity.BaseData
import com.ellricky.baselib.entity.ClassConsumeInfo
import com.ellricky.baselib.entity.IdNamePickerEntity
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEBaseCallback
import com.ellricky.baselib.util.NewEListCallBack2
import com.ellricky.baselib.util.TimeUtils
import kotlinx.android.synthetic.main.base_layout_class_consume.*
import java.util.*

class ClassConsumeFragment : BaseFragment<Void, BasePresenter<Void>>(), RvRefreshListener,
    AdapterView.OnItemClickListener {

    private var paramMap: HashMap<String, String> = hashMapOf()
    private var dataSource: List<ClassConsumeInfo> = arrayListOf()
    private var ePickerUtil: EPickerUtil? = null
    private var refresh = false

    private var mDateType = BaseConstant.MONTH_AND_DAY

    //日期 年月/年月日
    private var date: String =
        TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH_DAY)

    //查询用户id
    private var empEid = LocalCacheUtil.getUid()

    private var courseType: String = ""

    private var courseState: String = ""

    private val courseTypeList by lazy {
        val list = arrayListOf<IdNamePickerEntity>();
        list.add(IdNamePickerEntity("", "全部"))
        list.add(IdNamePickerEntity("2", "艺术创造"))
        list.add(IdNamePickerEntity("5", "美学基础"))
        list.add(IdNamePickerEntity("4", "艺术史"))
        list.add(IdNamePickerEntity("0", "赠课"))
        list
    }

    private val courseStateList by lazy {
        val list = arrayListOf<IdNamePickerEntity>();
        list.add(IdNamePickerEntity("", "全部"))
        list.add(IdNamePickerEntity("5", "上课"))
        list.add(IdNamePickerEntity("6", "请假"))
        list.add(IdNamePickerEntity("61", "停课"))
        list
    }

    private val adapter by lazy {
        ClassConsumeAdapter()
    }

    private val showBackIcon by lazy {
        arguments?.getBoolean(BaseConstant.KEY_SHOW_BACK) ?: true
    }

    companion object {
        fun newInstance(extras: Bundle?): ClassConsumeFragment {
            val fragment = ClassConsumeFragment()
            fragment.arguments = extras
            return fragment
        }
    }

    override fun getContentLayout(): Int {
        return R.layout.base_layout_class_consume
    }

    override fun initUIView(view: View?) {
        tv_title.text = "课消管理"

        rvView.init(this)

        ePickerUtil = EPickerUtil(requireActivity())

        initListener()
    }

    private fun initListener() {
        if (!showBackIcon) {
            ib_back.visibility = View.GONE
        }
        ib_back.setOnClickListener {
            activity?.also {
                it.finish()
            }
        }
        if (LocalCacheUtil.isPresidentRole()) {
            //选择人员
            tv_teacher?.setOnClickListener {
                ePickerUtil?.checkStaffTypePicker(null) { _, entry ->
                    tv_teacher.text = entry.name
                    empEid = entry.id
                    loadDataOnInit()
                }
            }
        } else {
            tv_teacher.text = LocalCacheUtil.readLocalUser().U_Name
            empEid = LocalCacheUtil.readLocalUser().id.toString()
        }

        //选择时间
        tv_date?.setOnClickListener {
            //yyyy-mm
            if (mDateType == BaseConstant.MONTH) {
                ePickerUtil?.showMonthMnPicker("") { content,
                                                     _,
                                                     _ ->
                    tv_date.text = TimeUtils.convertFormat(
                        content,
                        TimeUtils.FORMAT_DIVER_MONTH,
                        TimeUtils.FORMAT_MONTH
                    )
                    date = content ?: ""
                    loadDataOnInit()
                }
            } else {
                //yyyy-mm-dd
                ePickerUtil?.showDayMnPicker("") { content,
                                                   _,
                                                   _ ->
                    tv_date.text = TimeUtils.convertFormat(
                        content,
                        TimeUtils.FORMAT_DIVER_MONTH_DAY,
                        TimeUtils.FORMAT_MONTH_DAY
                    )
                    date = content ?: ""
                    loadDataOnInit()
                }
            }
        }

        tv_course_type.setOnClickListener {
            ePickerUtil?.showCustomPicker(courseTypeList, null) { _,
                                                                  content ->

                courseType = content.id
                tv_course_type.text = content.name
                loadDataOnInit()
            }
        }

        tv_course_state?.setOnClickListener {
            ePickerUtil?.showCustomPicker(courseStateList, null) { _,
                                                                   content ->

                courseState = content.id
                tv_course_state.text = content.name
                loadDataOnInit()
            }
        }

        switchmultibutton?.setOnSwitchListener { position, _ ->
            if (position == 0) {
                //yyyy-mm-dd
                date = TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH_DAY)
                mDateType = BaseConstant.MONTH_AND_DAY
                tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH_DAY)
            } else {
                //yyyy-mm
                date = TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH)
                mDateType = BaseConstant.MONTH
                tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH)
            }
            loadDataOnInit()
        }

        tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH_DAY)

        loadDataOnInit()
    }

    private fun initParamMap() {
        paramMap["action"] = "courseToMember"
        paramMap["eid"] = LocalCacheUtil.getUid()
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["page"] = rvView.getCurPage().toString()
        paramMap["emp_type"] = rvView.getCurPage().toString()
        paramMap["page_size"] = "40"
        paramMap["course_state"] = courseState
        paramMap["course_type"] = courseType
        paramMap["emp_type"] = getEmpType()
        paramMap["emp_id"] = empEid
        if (paramMap.containsKey("day")) {
            paramMap.remove("day")
        }
        if (paramMap.containsKey("month")) {
            paramMap.remove("month")
        }
        if (mDateType == BaseConstant.MONTH_AND_DAY) {
            paramMap["day"] = date
        } else {
            paramMap["month"] = date
        }
    }

    //服务端约定
    private fun getEmpType(): String {
        when {
            LocalCacheUtil.isPresidentRole() -> {
                return "0"
            }
            LocalCacheUtil.isTmRole() -> {
                return "1"
            }
            LocalCacheUtil.isTcRole() -> {
                return "2"
            }
            LocalCacheUtil.isConsultantRole() -> {
                return "3"
            }
            LocalCacheUtil.isMarketRole() -> {
                return "4"
            }
            else -> return ""
        }
    }

    private fun loadDataOnInit() {
        rvView.loadContent(true)
    }

    override fun loadData(refresh: Boolean) {
        this.refresh = refresh
        val url = EAppUtil.getApiHost()
        initParamMap()
        val callback: NewEBaseCallback = getResponseCallback2()
        HttpUtils.getInstance().postFrom(url, paramMap, callback)
    }

    private fun getResponseCallback2(): NewEBaseCallback {
        return object : NewEListCallBack2<ClassConsumeInfo>(requireActivity()) {
            override fun onSuccess(
                data: MutableList<ClassConsumeInfo>,
                basedata: BaseData<ClassConsumeInfo>,
                msg: String?
            ) {
                dataSource = data
                rvView.onLoadFinish(data, refresh)
                tv_order_number.text =
                    "出勤：${basedata.allcount - basedata.leavecount}   请假：${basedata.leavecount}    课消：${basedata.course_total}"

            }
        }
    }

    override fun updateAdapterData(refresh: Boolean) {
        if (refresh) adapter.refresh(dataSource)
        else adapter.loadMore(dataSource)
    }

    override fun setAdapter(rv: RecyclerView?) {
        rv?.adapter = adapter
    }


    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

    }
}